package Client;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

public class FileReciever extends Thread {

	private ServerSocket ss;
	private String filename;
	boolean isDone;

	public FileReciever(int port, String filename) {
		isDone = false;
		try {
			ss = new ServerSocket(port);
			this.filename = filename;
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(ss.getInetAddress().getHostAddress());
	}

	public void run() {
		Socket clientSock;
		while (!isDone) {
			try {
				clientSock = ss.accept();
				saveFile(clientSock);
				clientSock.close();
				isDone = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		JOptionPane.showMessageDialog(null, "The file is now downloaded!");
		try {
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InetAddress getAddress() {
		return ss.getInetAddress();

	}

	private void saveFile(Socket clientSock) throws IOException {
		DataInputStream dis = new DataInputStream(clientSock.getInputStream());
		FileOutputStream fos = new FileOutputStream(filename);
		byte[] buffer = new byte[4096];

		int read = 0;
		JOptionPane.showMessageDialog(null, "Starting download...");
		while ((read = dis.read(buffer, 0, buffer.length)) > 0) {
			System.out.println("Recieving!");
			fos.write(buffer, 0, read);
		}
		fos.close();
		dis.close();
	}

}
